﻿using UnityEngine;
using UnityEngine.UI;
/**
 * tips: Legacy类型的动画剪辑不能在AnimatorController中使用
 * 通过替换动画的方式，用需要播放的动画将控制器AnimatorController中指定的一个动画替换，间接达到动态加载的功能
 * 通过指定的stateName，替换掉控制器中的动画剪辑AnimationClip
 */
public class TestAniOverrodeCtr : MonoBehaviour
{
    public Animator m_Animator;
    public RuntimeAnimatorController m_RuntimeAnimatorController;
    public AnimationClip[] clips;
    string mOriginClipName = "";
    public Button rotationBtn;
    public Button moveBtn;
    public Button stopBtn;

    private void Start()
    {
        rotationBtn.onClick.AddListener((PlayRotationAni));
        moveBtn.onClick.AddListener((PlayPositionAni));
        stopBtn.onClick.AddListener((StopAni));
    }

    private void PlayPositionAni()
    {
        UpDateAnimator();
    }

    private void PlayRotationAni()
    {
        m_Animator.enabled = true;
        m_Animator.Play("rotation");
    }

    private void StopAni()
    {
        m_Animator.enabled = false;
    }

    /// <summary>
    /// 更新动画，会改变当前stateName对应的clip，
    /// 例如：当前播放的的“rotation” 被override后，下次Play("rotation")的时候用的就不是原来的rotationClip了
    /// </summary>
    void UpDateAnimator()
    {
        m_Animator.enabled = true;
        
        // 获取当前动画的 clipName， 获取不到stateName通过对比选择stateName
        string  animString = m_Animator.GetCurrentAnimatorClipInfo(0)[0].clip.name;
        if (!m_Animator.GetCurrentAnimatorStateInfo(0).IsName(animString) && mOriginClipName != "") // stateName 和 clipName 不一致
        {
            animString = mOriginClipName; // 使用 上次的stateName
        }
        else
        {
            mOriginClipName = animString;
        }
        
        var clip = clips[0];
        var tOverrideController = new AnimatorOverrideController();
        tOverrideController.runtimeAnimatorController = m_RuntimeAnimatorController;
        tOverrideController[animString] = clip;
        
        m_Animator.runtimeAnimatorController = null;
        m_Animator.runtimeAnimatorController = tOverrideController;
        m_Animator.Play(animString, 0, 0);
        
        /**
         * m_Animator.runtimeAnimatorController = null;
         *  Resources.UnloadUnusedAssets(); 如果是动态加载动画clip
         * 两行很关键，没有这两行，会出现错乱或者内存持续增加
         */
    }
}